package com.example.a24porint;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Random;

public class onlinegame extends AppCompatActivity implements View.OnClickListener {

    int[] num = new int[4];
    int[][] color = new int[3][];
    private Button[] bt = new Button[4];
    private Button[] wy = new Button[5];
    private Button chexiao = null;
    private Button zhunbei = null;
    private Button huan1ti = null;
    private Socket socket =null;
    private String receiveMsg;
    private OutputStream outputStream;
    private InputStream inputStream;
    private BufferedReader in;
    private TextView wtext;
    private TextView statustext;
    private Boolean losestatus=false;
    private Boolean winstatus=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_onlinegame);
        init();
    }

    private void hideall()
    {
        bt[0].setVisibility(View.INVISIBLE);
        bt[1].setVisibility(View.INVISIBLE);
        bt[2].setVisibility(View.INVISIBLE);
        bt[3].setVisibility(View.INVISIBLE);
        wy[1].setVisibility(View.INVISIBLE);
        wy[2].setVisibility(View.INVISIBLE);
        wy[3].setVisibility(View.INVISIBLE);
        wy[4].setVisibility(View.INVISIBLE);
        chexiao.setVisibility(View.INVISIBLE);
        huan1ti.setVisibility(View.INVISIBLE);
    }
    private void showall()
    {
        zhunbei.setVisibility(View.INVISIBLE);
        bt[0].setVisibility(View.VISIBLE);
        bt[1].setVisibility(View.VISIBLE);
        bt[2].setVisibility(View.VISIBLE);
        bt[3].setVisibility(View.VISIBLE);
        wy[1].setVisibility(View.VISIBLE);
        wy[2].setVisibility(View.VISIBLE);
        wy[3].setVisibility(View.VISIBLE);
        wy[4].setVisibility(View.VISIBLE);
        chexiao.setVisibility(View.VISIBLE);
        //huan1ti.setVisibility(View.VISIBLE);
    }
    public void turncolor(View v) {
        switch (v.getId()) {
            case R.id.button:
                if (color[0][0] == 0) {
                    ((Button) v).setBackgroundColor(Color.parseColor("#4AFA00"));
                    color[0][0] = 1;
                } else {
                    ((Button) v).setBackgroundColor(Color.parseColor("#A0FF78"));
                    color[0][0] = 0;
                }
                break;
            case R.id.button2:
                if (color[0][2] == 0) {
                    ((Button) v).setBackgroundColor(Color.parseColor("#4AFA00"));
                    color[0][2] = 1;
                } else {
                    ((Button) v).setBackgroundColor(Color.parseColor("#A0FF78"));
                    color[0][2] = 0;
                }
                break;
            case R.id.button3:
                if (color[2][0] == 0) {
                    ((Button) v).setBackgroundColor(Color.parseColor("#4AFA00"));
                    color[2][0] = 1;
                } else {
                    ((Button) v).setBackgroundColor(Color.parseColor("#A0FF78"));
                    color[2][0] = 0;
                }
                break;
            case R.id.button5:
                if (color[2][2] == 0) {
                    ((Button) v).setBackgroundColor(Color.parseColor("#4AFA00"));
                    color[2][2] = 1;
                } else {
                    ((Button) v).setBackgroundColor(Color.parseColor("#A0FF78"));
                    color[2][2] = 0;
                }
                break;
            case R.id.button8:
                if (color[1][0] == 0) {
                    ((Button) v).setBackgroundColor(Color.parseColor("#4AFA00"));
                    color[1][0] = 1;
                } else {
                    ((Button) v).setBackgroundColor(Color.parseColor("#A0FF78"));
                    color[1][0] = 0;
                }
                break;
            case R.id.button9:
                if (color[1][2] == 0) {
                    ((Button) v).setBackgroundColor(Color.parseColor("#4AFA00"));
                    color[1][2] = 1;
                } else {
                    ((Button) v).setBackgroundColor(Color.parseColor("#A0FF78"));
                    color[1][2] = 0;
                }
                break;
            case R.id.button6:
                if (color[0][1] == 0) {
                    ((Button) v).setBackgroundColor(Color.parseColor("#4AFA00"));
                    color[0][1] = 1;
                } else {
                    ((Button) v).setBackgroundColor(Color.parseColor("#A0FF78"));
                    color[0][1] = 0;
                }
                break;
            case R.id.button7:
                if (color[2][1] == 0) {
                    ((Button) v).setBackgroundColor(Color.parseColor("#4AFA00"));
                    color[2][1] = 1;
                } else {
                    ((Button) v).setBackgroundColor(Color.parseColor("#A0FF78"));
                    color[2][1] = 0;
                }
                break;
            default:
                break;
        }
    }
    @Override
    public void onClick(View v) {
        //#4AFA00
        // ((Button)v).setBackgroundColor();
        turncolor(v);
        switch (v.getId()) {
            case R.id.button12:
                hideready();
                break;
            case R.id.button10:
                resetall();
                break;
            case R.id.button11:
                huan1tirun();
                break;
            case R.id.button:
            case R.id.button2:
            case R.id.button3:
            case R.id.button5:
                onClickButton(v);
                break;
            case R.id.button8:
                way = 1;
                break;
            case R.id.button9:
                way = 2;
                break;
            case R.id.button6:
                way = 3;
                break;
            case R.id.button7:
                way = 4;
                break;
            default:
                break;
        }
    }

    private void huan1tirun() {
        Random a = new Random();
        for (int i = 0; i < 4; i++) {
            num[i] = a.nextInt(14);
            resetall();
        }
    }

    private void resetall() {
        //initgame();
        c1 = 0;
        diyishu = 0;
        remain = 4;
        way = 0;
        strdiyishu = "";
        buttontemp = null;
        for (int i = 0; i < 4; i++) {
            bt[i].setText("" + num[i]);
            bt[i].setVisibility(View.VISIBLE);
        }
    }

    private int c1 = 0, diyishu = 0, remain = 4, way = 0;
    private String strdiyishu = "";
    private Button buttontemp;

    private void onClickButton(View v) {
        String str = ((Button) v).getText().toString();
        if (c1 == 0) {
            c1 = 1;
            /*if(existchu(str))
            {
                diyishu=-5201314;
                strdiyishu=str;
            }
            else
            diyishu=Integer.valueOf(str);*/
            buttontemp = (Button) v;
        } else if (c1 == 1 && way == 0) {
            turncolor(v);
            turncolor(buttontemp);
            /*if(existchu(str))
            {
                diyishu=-5201314;
                strdiyishu=str;
            }
            else
            diyishu=Integer.valueOf(str);*/
            buttontemp = (Button) v;
        } else if (c1 == 1 && way != 0) {
            String strresult = calculation(buttontemp, (Button) v);
            if (strresult != "") {
                buttontemp.setText(strresult);
                turncolor(buttontemp);
                turncolor(v);
                turncolor(wy[way]);
                way = 0;
                c1 = 0;
                remain--;
                if (remain == 1) {
                    //wy[1].setText("24你信吗？");
                    int theresult = 0;
                    for (int i = 0; i < 4; i++) {
                        if (bt[i].getVisibility() != View.INVISIBLE)
                            theresult = Integer.valueOf(bt[i].getText().toString());
                    }
                    if(losestatus)
                    {
                        lose();
                    }
                    else if (theresult == 24) {
                        win();
                        Toast ts = Toast.makeText(getBaseContext(), "你赢了", Toast.LENGTH_LONG);
                        ts.show();
                    } else {
                        Toast ts = Toast.makeText(getBaseContext(), "结果不等于24，请点击撤销", Toast.LENGTH_LONG);
                        ts.show();
                    }
                }
            }
        }
    }

    private boolean existchu(String str) {
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == '/') return true;
        }
        return false;
    }

    private String chucal(String str1, String str2) {
        int str1qian = 0, str1hou = 0, str2qian = 0, str2hou = 0;
        String strresult = "";
        if (existchu(str1)) {
            int chusitu = -1;
            for (int i = 0; i < str1.length(); i++) {
                if (str1.charAt(i) != '/') {
                    str1qian += (int) str1.charAt(i) - (int) '0';
                    str1qian *= 10;
                } else {
                    chusitu = i;
                    str1qian /= 10;
                    break;
                }
            }
            if (chusitu != -1) {
                for (int i = chusitu + 1; i < str1.length(); i++) {
                    str1hou += (int) str1.charAt(i) - (int) '0';
                    str1hou *= 10;
                }
                str1hou /= 10;
            }
        } else {
            for (int i = 0; i < str1.length(); i++) {
                str1qian += (int) str1.charAt(i) - (int) '0';
                str1qian *= 10;
            }
            str1hou = 1;
            str1qian /= 10;
        }
        if (existchu(str2)) {
            int chusitu = -1;
            for (int i = 0; i < str2.length(); i++) {
                if (str2.charAt(i) != '/') {
                    str2qian += (int) str2.charAt(i) - (int) '0';
                    str2qian *= 10;
                } else {
                    chusitu = i;
                    str2qian /= 10;
                    break;
                }
            }
            if (chusitu != -1) {
                for (int i = chusitu + 1; i < str2.length(); i++) {
                    str2hou += (int) str2.charAt(i) - (int) '0';
                    str2hou *= 10;
                }
                str2hou /= 10;
            }

        } else {
            for (int i = 0; i < str2.length(); i++) {
                str2qian += (int) str2.charAt(i) - (int) '0';
                str2qian *= 10;
            }
            str2qian /= 10;
            str2hou = 1;
        }
        if (str1hou != str2hou) {
            str1qian *= str2hou;
            str2qian *= str1hou;
            str1hou *= str2hou;
            str2hou = str1hou;
        }
        //System.out.println(str1qian+"/"+str1hou);
        //System.out.println(str2qian+"/"+str2hou);
        switch (way) {
            case 1:
                str1qian += str2qian;
                strresult += new String("" + str1qian + "/" + str1hou);
                strresult = yuefen(strresult);
                break;
            case 2:
                str1qian -= str2qian;
                strresult += new String("" + str1qian + "/" + str1hou);
                strresult = yuefen(strresult);
                break;
            case 3:
                str1qian *= str2qian;
                str1hou *= str2hou;
                strresult += new String("" + str1qian + "/" + str1hou);
                strresult = yuefen(strresult);
                break;
            case 4:
                str1qian *= str2hou;
                str1hou *= str2qian;
                strresult += new String("" + str1qian + "/" + str1hou);
                strresult = yuefen(strresult);
                break;
            default:
                break;
        }
        return strresult;
    }

    private String yuefen(String str1) {
        int str1qian = 0, str1hou = 0, chusitu = 0;
        String result = "";
        for (int i = 0; i < str1.length(); i++) {
            if (str1.charAt(i) != '/') {
                str1qian += (int) str1.charAt(i) - (int) '0';
                str1qian *= 10;
            } else {
                chusitu = i;
                str1qian /= 10;
                break;
            }
        }
        for (int i = chusitu + 1; i < str1.length(); i++) {
            str1hou += (int) str1.charAt(i) - (int) '0';
            str1hou *= 10;
        }
        str1hou /= 10;
        if (str1qian % str1hou == 0) {
            str1qian /= str1hou;
            result = new String("" + str1qian);
        } else {
            int a = gcd(str1qian, str1hou);
            str1qian /= a;
            str1hou /= a;
            result = new String("" + str1qian + "/" + str1hou);
        }
        return result;
    }

    public int gcd(int m, int n) {
        int result = 0;
        while (n != 0) {
            result = m % n;
            m = n;
            n = result;
        }
        return m;
    }

    private String calculation(Button b1, Button b2) {
        if (b1.equals(b2)) {
            //turncolor(b1);
            return "";
        }
        if (way == 0) return "";
        int result = 0;
        int a1 = 0, a2 = 0;
        String str1 = b1.getText().toString(), str2 = b2.getText().toString(), strresult = "";
        if (existchu(str1) || existchu(str2)) {
            strresult = chucal(str1, str2);
            b2.setVisibility(View.INVISIBLE);
            return strresult;
        } else {
            a1 = Integer.valueOf(str1);
            a2 = Integer.valueOf(str2);
            switch (way) {
                case 1:
                    a1 += a2;
                    break;
                case 2:
                    a1 -= a2;
                    break;
                case 3:
                    a1 *= a2;
                    break;
                case 4:
                    if (a1 % a2 == 0)
                        a1 /= a2;
                    else {
                        b2.setVisibility(View.INVISIBLE);
                        return a1 + "/" + a2;
                    }
                    break;
                default:
                    break;
            }
        }
        b2.setVisibility(View.INVISIBLE);
        return new String("" + a1);
    }

    public void init() {
        ApplicationUtil appUtil =  (ApplicationUtil) onlinegame.this.getApplication();
        try {
            appUtil.init();
            socket = appUtil.getSocket();
            outputStream=appUtil.getOutputStream();
            inputStream=appUtil.getInputStream();
            if(socket==null)
            Log.i("initerrortag","===========================--------------------");
        } catch (Exception e) {
            e.printStackTrace();
            Log.i("initerrortag","wjoafjaoisdjfoiasdjf--------------------");
        }
        for (int i = 0; i < 3; i++) {
            color[i] = new int[3];
        }
        bt[0] = findViewById(R.id.button);
        //bt[0].setBackgroundColor(Color.parseColor("#4AFA00"));
        //bt[0].setBackgroundColor(Color.parseColor("#A0FF78"));
        bt[1] = findViewById(R.id.button2);
        bt[2] = findViewById(R.id.button3);
        bt[3] = findViewById(R.id.button5);
        wy[1] = findViewById(R.id.button8);
        wy[2] = findViewById(R.id.button9);
        wy[3] = findViewById(R.id.button6);
        wy[4] = findViewById(R.id.button7);
        chexiao = findViewById(R.id.button10);
        huan1ti = findViewById(R.id.button11);
        zhunbei = findViewById(R.id.button12);
        statustext=findViewById(R.id.textView4);
        wtext=findViewById(R.id.Waitingtext);
        hideall();   //bug
        bt[0].setOnClickListener(this);
        bt[1].setOnClickListener(this);
        bt[2].setOnClickListener(this);
        bt[3].setOnClickListener(this);
        wy[1].setOnClickListener(this);
        wy[2].setOnClickListener(this);
        wy[3].setOnClickListener(this);
        wy[4].setOnClickListener(this);
        chexiao.setOnClickListener(this);
        huan1ti.setOnClickListener(this);
        zhunbei.setOnClickListener(this);    //bug
        receivemsg();
    }
    private void hideready() {
        zhunbei.setVisibility(View.INVISIBLE);
        wtext.setVisibility(View.VISIBLE);
        sendready();
    }

    private void initgame() {
        String str = null;
        str=login;
        if(login==null);//chexiao.setText("aowefjoiawe");
        if (str!=null&&str.charAt(0) == 'y') {
            num[0] = (str.charAt(1) - (int) '0') * 10 + str.charAt(2) - (int) '0';
            num[1] = (str.charAt(4) - (int) '0') * 10 + str.charAt(5) - (int) '0';
            num[2] = (str.charAt(7) - (int) '0') * 10 + str.charAt(8) - (int) '0';
            num[3] = (str.charAt(10) - (int) '0') * 10 + str.charAt(11) - (int) '0';
        }
        for(int i=0;i<4;i++)
        {
            bt[i].setText(new String(String.valueOf(num[i])));
        }
    }
    String login=null;
    private void win()
    {
        zhunbei.setVisibility(View.VISIBLE);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    winstatus=true;
                    String str="playingwin";
                    byte[] str_head=str.getBytes();
                    outputStream.write(str_head);
                    Log.i("wintag","winisok");
                    /*in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
                    receiveLoginMsg();
                    initgame();*/
                    //initLoginThread();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void sendready()
    {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    losestatus=false;
                    String str="playingwait";
                    byte[] str_head=str.getBytes();
                    outputStream.write(str_head);
                    Log.i("sendreadytag","isok"+str);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private boolean islose(String s)
    {
        String str="lose";
        if(s.length()<str.length())return false;
        for(int i=0;i<str.length();i++)
        {
            if(str.charAt(i)!=s.charAt(i))
            {
                return false;
            }
        }
        return true;
    }
    Thread receivemsgthread;
    private void receivemsg()
    {
        final String[] receiveMsg = new String[1];
        Thread thread= new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                    while (true) {
                        receiveMsg[0] = in.readLine();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                statustext.setText(receiveMsg[0]);
                            }
                        });
                        if((receiveMsg[0]) != null&&islose(receiveMsg[0]))
                        {
                            lose();
                        }
                        else if((receiveMsg[0]) != null&&receiveMsg[0].charAt(0)=='y')
                        {
                            login=receiveMsg[0];
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    wtext.setVisibility(View.INVISIBLE);
                                    initgame();
                                    showall();
                                    resetall();
                                }
                            });
                            Log.i("receivemsg","it s ok;");
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });//.start();
        receivemsgthread=thread;
        thread.start();
    }
    private void lose()
    {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                losestatus=true;
                zhunbei.setVisibility(View.VISIBLE);
                Toast ts = Toast.makeText(getBaseContext(), "对手比你快得出24点 你输了", Toast.LENGTH_LONG);
                ts.show();
            }
        });
    }
    private void receivelose() throws IOException {
        while (true) {                   //步骤三
            if(winstatus){winstatus=false;break;}

        }
    }
    private void receiveLoginMsg() throws IOException {
        while (true) {                   //步骤三
                if ((receiveMsg = in.readLine()) != null&&receiveMsg.length()>10) {
                login=receiveMsg;
                break;
            }
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                wtext.setVisibility(View.INVISIBLE);
                initgame();
                showall();
                resetall();
            }
        });
    }
}
    /*private void getlosestatus()
    {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                    receivelose();
                    Log.i("getlosestautstag","getlosestautsisok");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }*/